package com.xhui.vimarket.zkplus.zul.attr.mod.impl;t java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.directwebremoting.util.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Div;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Popup;
import org.zkoss.zul.Span;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treeitem;

import com.xhui.crm.common.ResConstants;
import com.xhui.crm.common.util.numeric.NumericUtil;
import com.xhui.crm.common.util.string.StrUtil;com.xhui.vimarket.zkplusui.vimarket.zkplus.util.com.xhui.vimarket.zkplusrt com.xhui.vimarket.zkpcom.xhui.vimarket.zkplusil;
import com.xhui.vicom.xhui.vimarket.zkplustil.ZkUtils;
import com.xhcom.xhui.vimarket.zkpluslus.zul.attr.AttrExt;
import comcom.xhui.vimarket.zkpluszkplus.zul.attr.bean.AttrInst;
icom.xhui.vimarket.zkplusvimarket.zkplus.zul.attr.bean.Acom.xhui.vimarket.zkplust com.xhui.vimarket.zkplus.zul.attr.bean.ValiVo;
import com.xhui.vimarket.zkplus.zul.attr.mod.AttrCompUtil;

/**
 * 生成树状下拉框控件.
 * 
 * @版权：福富软件 版权所有 (c) 2011
 * @author Liuzhuangfei
 * @version Revision 1.0.0
 * @see:
 * @创建日期： 2011-10-11
 * @功能说明：
 */
@SuppressWarnings("deprecation")
public class AttrSelectTreeComp extends AttrBaseComp {
    
    /**
     * 实例.
     */
    private static AttrSelectTreeComp inst   = new AttrSelectTreeComp();
    
    /**
     * 日志.
     */
    private static Logger             logger = Logger.getLogger(AttrSelectTreeComp.class);
    
    /**
     * .
     */
    private String                    className;
    
    /**
     * .
     */
    private String                    propertyName;
    
    /**
     * 构造函数. 
     */
    protected AttrSelectTreeComp() {
    }
    
    /**
     * 获取实例.
     * 
     * @return AttrBaseComp
     */
    public static AttrSelectTreeComp instance() {
        return AttrSelectTreeComp.inst;
    }
    
    /**
     * 生成组件.
     * @param attrExt 组件控件
     * @param attrTmpl 组件模板
     * @param comp 显示容器组件
     */
    
    @Override
    public void create(final AttrExt attrExt, final AttrTmpl attrTmpl, final Component comp) {
        super.create(attrExt, attrTmpl, comp);
        
        final Hbox hbox = new Hbox();
        //1. 设置hbox对象的相关ATTR_SPEC属性信息
        genHbox(hbox, attrTmpl);
        hbox.setParent(comp);
        hbox.setVflex("1");
        
        //2. 生成规格树
        final Div labDiv = new Div();
        // info
        final Span infDiv = this.createRulebar(attrExt, labDiv, attrTmpl);
        final Label label = new Label(attrTmpl.getName());
        label.setSclass("zp-lt-label");
        labDiv.setParent(hbox);
        label.setParent(labDiv);
        infDiv.setParent(labDiv);
        
        // content
        final Div divcont = new Div();
        divcont.setParent(hbox);
        final Textbox textbox = new Textbox();
        textbox.setReadonly(true);
        textbox.setStyle("width:78%;");
        textbox.setParent(divcont);
        Button btn = new Button();
        btn.setStyle("width:28px;height:21px;");
        btn.setImage(ResConstants.IMG_FIND);
        btn.setParent(divcont);
        final Popup pop = new Popup();
        pop.setParent(divcont);
        
        // tree div
        Div div = new Div();
        div.setStyle("width:600px;");
        div.setParent(pop);
        genDiv(div, attrTmpl);
        // div.setParent(bandPopup);
        div.setVflex("1");
        //div.setHflex("1");
        final Tree attrValueTree = (Tree) attrExt.getAttrAda().getAttrTmplCompStr(
            attrTmpl.getDisplayMode(), attrTmpl, attrTmpl.getParam2(), null, null, div);
        if (ZkUtils.isBrowser("ie6-")) {
            pop.setStyle("width:620px;");
            attrValueTree.setStyle("width:600px;");
        }
        attrValueTree.addEventListener(Events.ON_SELECT, new EventListener() { // 树节点选中
                @Override
                public void onEvent(Event event) throws Exception {
                    final Treeitem selectedItem = ((Tree) attrValueTree).getSelectedItem();
                    if (selectedItem != null
                        && !"".equals(StrUtil.strnull(selectedItem.getValue()))) { // 有选中值
                        textbox.setAttribute(AttrBaseComp.COMP_PARAM1, StrUtil.strnull(selectedItem
                            .getValue()));
                        textbox.setAttribute(AttrBaseComp.COMP_PARAM2, StrUtil.strnull(selectedItem
                            .getLabel()));
                        textbox.setValue(selectedItem.getLabel());
                        textbox.setTooltiptext(selectedItem.getLabel());
                    } else {
                        textbox.removeAttribute(AttrBaseComp.COMP_PARAM1);
                        textbox.removeAttribute(AttrBaseComp.COMP_PARAM2);
                        textbox.setValue("");
                        textbox.setTooltiptext("");
                    }
                    pop.close();
                }
            });
        //Tree attrValueTree = new Tree();
        //attrValueTree.setWidth(AttrBaseComp.WIDTH_SELECT);
        if (attrTmpl.getAttrValueMapList() != null) {
            genTree(attrTmpl.getAttrValueMapList(), attrValueTree, 0L);
        }
        btn.addEventListener(Events.ON_CLICK, new EventListener() { // 点击按钮打开popuptree
                @Override
                public void onEvent(Event event) throws Exception {
                    pop.open(textbox, "after_start");
                    // 自动选中
                    String val = StrUtil.strnull(textbox.getAttribute(AttrBaseComp.COMP_PARAM1));
                    AttrSelectTreeComp.selectByCodeValue(attrValueTree, val);
                }
            });
        //attrValueTree.setParent(div);
        attrValueTree.setWidth("200%");
        attrValueTree.setVflex("1");
        attrValueTree.setZclass("z-dottree");
        attrValueTree.setMold("paging");
        attrValueTree.setPageSize(10);
        // last
        final Div divtool = new Div();
        divtool.setParent(hbox);

        
        super.afterCreate(attrExt, attrTmplcom.xhui.vimarket.zkplus
    
    @Override
    /**
     * {@inheritDoc}
     * @see com.xhui.vimarket.zkplus.zul.attr.mod.AttrComp
     * #setAttrView(org.zkoss.zk.ui.Component, Map<String, Integer>)
     * @author Liuzhuangfei
     * 2011-6-16 Liuzhuangfei
     */
    public void setAttrView(final Component comp, Map<String, Integer> attrViewMap) {
        if (attrViewMap != null && attrViewMap.size() > 0) {
            String attrJC = comp.getAttribute(AttrBaseComp.COMP_JAVACODE) + "";
            if (!StrUtil.isNullOrEmpty(attrJC)) {
                Integer viewType = attrViewMap.get(attrJC);
                // 获取树
                final Tree compTree = getTree(comp);
                if (compTree != null) {
                    compTree.setVisible(false);
                    if (AttrBaseComp.VIEW_TYPE_SHOW == viewType) {
                        compTree.setVisible(true);
                    } else if (AttrBaseComp.VIEW_TYPE_EDIT == viewType) {
                        compTree.setVisible(true);
                    }
                }
            }
        }
    }
    
    /**
     * 设置值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @param attrInstList 属性实例
     */
    @Override
    public void setValue(final AttrExt attrExt, final Component comp,
        final List<AttrInst> attrInstList, final Map<String, Integer> attrViewMap) {
        super.setValue(attrExt, comp, attrInstList, attrViewMap);
        //列表
        final Component compTree = getTree(comp);
        if (compTree != null) {
            final long theAttrId = NumUtils
                .toLong("" + comp.getAttribute(AttrBaseComp.COMP_ATTRID));
            final ArrayList<AttrInst> theAttrList = AttrBaseComp.getAttrInstListById(attrInstList,
                theAttrId);
            if (theAttrList.size() > 0) {
                setByCodeValue((Tree) compTree, theAttrList.get(0).getParam1(), comp);
                // javacode回填
                AttrCompUtil.copyTmplInfo(theAttrList.get(0), comp);
            }
        }
    }
    
    /**
     * 获取值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @return ArrayList<AttrInst>
     */
    @Override
    public ArrayList<AttrInst> getValue(final AttrExt attrExt, final Component comp) {
        super.getValue(attrExt, comp);
        final ArrayList<AttrInst> retList = new ArrayList<AttrInst>();
        // 取列表
        final Component compTree = getTree(comp);
        if (compTree != null) {
            Textbox textbox = getTextbox(comp);
            String value = StrUtil.strnull(textbox.getAttribute(AttrBaseComp.COMP_PARAM1));
            if (!StrUtil.isNullOrEmpty(value)) { // 有选中值
                final AttrInst attrInst = attrExt.newAttrInst();
                attrInst.setAttrId(NumUtils
                    .toLong("" + comp.getAttribute(AttrBaseComp.COMP_ATTRID)));
                attrInst
                    .setJavaCode(StrUtil.strnull(comp.getAttribute(AttrBaseComp.COMP_JAVACODE)));
                // attrInst.setParam1(StrUtil.strnull(selectedItem.getValue()));
                attrInst.setOp(this.getToolbarOp(comp));
                retList.add(attrInst);
                attrInst.setParam1(StrUtil.strnull(textbox.getAttribute(AttrBaseComp.COMP_PARAM1)));
                attrInst.setParam2(StrUtil.strnull(textbox.getAttribute(AttrBaseComp.COMP_PARAM2)));
            }
        }
        ((Popup) compTree.getParent().getParent()).ccom.xhui.vimarket.zkplus  return retList;
    }
    
    /**
    com.xhui.vimarket.zkplus}
     * @see com.xhui.vimarket.zkplus.zul.attr.mod.impl.AttrBaseComp#signRuleHint(com.xhui.vimarket.zkplus.zul.attr.AttrExt, org.zkoss.zk.ui.Component)
     * @author wuyx
     * 2012-2-16 wuyx
     */
    @Override
    public ArrayList<ValiVo> signRuleHint(AttrExt attrExt, Component comp) {
        super.signRuleHint(attrExt, comp);
        if (AttrCompUtil.isCantNull(comp)) { // 必填
            ArrayList<AttrInst> valList = this.getValue(attrExt, comp);
            if (valList == null || valList.size() < 1) {
                ValiVo retVo = new ValiVo();
                ArrayList<ValiVo> retVoList = new ArrayList<ValiVo>();
                retVoList.add(retVo);
                return retVoList;
            }
        }
        return null;
    }
    
    /**
     * 取空值属性实例.
     * 
     * @param attrExt 组件控件
     * @param attrTmpl 模板
     * @return ArrayList<AttrInst>
     */
    @Override
    public ArrayList<AttrInst> getNullValue(final AttrExt attrExt, final AttrTmpl attrTmpl) {
        super.getNullValue(attrExt, attrTmpl);
        final ArrayList<AttrInst> retList = new ArrayList<AttrInst>();
        final AttrInst attrInst = attrExt.newAttrInst();
        attrInst.setAttrId(attrTmpl.getAttrId());
        attrInst.setJavaCode(attrTmpl.getJavaCode());
        retList.add(attrInst);
        return retList;
    }
    
    /**
     * 清空值.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     */
    @Override
    public void clean(final AttrExt attrExt, final Component comp) {
        super.clean(attrExt, comp);
    }
    
    /**
     * 设置为不允许修改.
     * 
     * @param attrExt 组件控件
     * @param comp 组件
     * @param tflag 设置值，true/false
     */
    @Override
    public void setDisabled(AttrExt attrExt, Component comp, boolean tflag) {
        super.setDisabled(attrExt, comp, tflag);
        ZkUiUtil.setDisabled(comp, tflag);
    }
    
    /**
     * 
     * .
     * 
     * @param list List<Map<String, Object>>
     * @param comp Component
     * @param parentValueId parentValueId
     * @author g.huangwch
     * 2011-10-14 g.huangwch
     */
    private static void genTree(List<Map<String, Object>> list, Component comp, Long parentValueId) {
        for (Map<String, Object> map : list) {
            if ((NumericUtil.nullToLongZero(map.get("parent_value_id")).longValue() == parentValueId
                .longValue())) {
                Treeitem subTreeitem = new Treeitem();
                subTreeitem.setValue(StrUtil.strnull(map.get("attr_value")));
                subTreeitem.setOpen(false);
                
                subTreeitem.setLabel(StrUtil.strnull(map.get("attr_value_name")));
                subTreeitem.setTooltiptext(StrUtil.strnull(map.get("attr_value_name")));
                
                genTree(list, subTreeitem, NumericUtil.nullToLongZero(map.get("attr_value_id")));
                
                if (comp instanceof Tree) {
                    Tree tree = (Tree) comp;
                    Treechildren treechildren = tree.getTreechildren();
                    if (treechildren == null) {
                        treechildren = new Treechildren();
                        tree.appendChild(treechildren);
                    }
                    treechildren.appendChild(subTreeitem);
                }
                
                if (comp instanceof Treeitem) {
                    Treeitem treeitem = (Treeitem) comp;
                    Treechildren treechildren = treeitem.getTreechildren();
                    if (treechildren == null) {
                        treechildren = new Treechildren();
                        treeitem.appendChild(treechildren);
                    }
                    treechildren.appendChild(subTreeitem);
                }
                
            }
        }
    }
    
    public static void changeRangeTree(List<Map<String, Object>> attrValueMapList, Component comp) {
        if (comp instanceof Tree) {
            Tree tree = (Tree) comp;
            if (tree != null) {
                //tree.clear();
                if (tree.getTreechildren() != null) {
                    tree.getTreechildren().detach();
                }
            }
            AttrSelectTreeComp.genTree(attrValueMapList, tree, 0L);
        }
    }
    
    /**
     * 方法功能:
     * 设置hbox的相关属性和展示方式 .
     * @param hbox Hbox
     * @param attrTmpl AttrTmpl
     * @author: Liuzhuangfei
     * @修改记录： 
     * ==============================================================<br>
     * 日期:2011-10-19 Liuzhuangfei 创建方法，并实现其功能
     * ==============================================================<br>
     */
    private void genHbox(Hbox hbox, AttrTmpl attrTmpl) {
        hbox.setSclass("zh-hbox-widths");
        hbox.setAttribute(AttrBaseComp.COMP_MODE, attrTmpl.getDisplayMode());
        hbox.setAttribute(AttrBaseComp.COMP_ATTRID, attrTmpl.getAttrId());
        hbox.setAttribute(AttrBaseComp.COMP_JAVACODE, attrTmpl.getJavaCode());
        hbox.setAttribute(AttrBaseComp.COMP_CANTNULL, AttrCompUtil.getStrCantNull(attrTmpl
            .isCantNull()));
        hbox.setAttribute(AttrBaseComp.COMP_COMP_NAME, attrTmpl.getName());
        
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_LENGTH, attrTmpl.getValueLength());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_FROM, attrTmpl.getValueFrom());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_TO, attrTmpl.getValueTo());
        AttrCompUtil.setCompAttr(hbox, AttrBaseComp.COMP_VALUE_REX, attrTmpl.getValidExpr());
        
        hbox.setWidth("100%");
        hbox.setWidths(this.getWidthsLCT(attrTmpl));
    }
    
    /**
     * 设置div的相关属性
     * .
     * 
     * @param div Div
     * @param attrTmpl AttrTmpl
     * @author g.huangwch
     * 2011-10-26 g.huangwch
     */
    private void genDiv(Div div, AttrTmpl attrTmpl) {
        div.setAttribute(AttrBaseComp.COMP_MODE, attrTmpl.getDisplayMode());
        div.setAttribute(AttrBaseComp.COMP_ATTRID, attrTmpl.getAttrId());
        div.setAttribute(AttrBaseComp.COMP_JAVACODE, attrTmpl.getJavaCode());
        div.setAttribute(AttrBaseComp.COMP_CANTNULL, AttrCompUtil.getStrCantNull(attrTmpl
            .isCantNull()));
        div.setAttribute(AttrBaseComp.COMP_COMP_NAME, attrTmpl.getName());
        
        //toolbar
        Toolbar queryBar = new Toolbar();
        queryBar.setWidth("199%");
        queryBar.setHeight("28px");
        queryBar.setParent(div);
        Textbox text = new Textbox();
        text.setValue("");
        Button btn = new Button(); // 定位
        btn.setLabel("定位");
        btn.setStyle("margin-left:2px;");
        text.setParent(queryBar);
        btn.setParent(queryBar);
        text.addEventListener(Events.ON_OK, new EventListener() {
            public void onEvent(final Event event) throws Exception {
                Component thiscomp = event.getTarget();
                Textbox text = (Textbox) thiscomp;
                String key = (text.getValue() + "").toLowerCase().trim();
                Tree tree = (Tree) thiscomp.getParent().getNextSibling();
                Collection<Treeitem> items = tree.getItems();
                if (items != null) {
                    for (Treeitem item : items) {
                        AttrSelectTreeComp.this.filterKey(item, key);
                    }
                }
                
            }
        });
        
        btn.addEventListener(Events.ON_CLICK, new EventListener() {
            public void onEvent(final Event event) throws Exception {
                Component thiscomp = event.getTarget();
                Textbox text = (Textbox) thiscomp.getPreviousSibling();
                String key = (text.getValue() + "").toLowerCase().trim();
                Tree tree = (Tree) thiscomp.getParent().getNextSibling();
                Collection<Treeitem> items = tree.getItems();
                if (items != null) {
                    for (Treeitem item : items) {
                        AttrSelectTreeComp.this.filterKey(item, key);
                    }
                }
                
            }
        });
        Button btn2 = new Button(); // 全部
        btn2.setLabel("全部");
        btn2.setParent(queryBar);
        btn2.setStyle("margin-left:2px;");
        btn2.addEventListener(Events.ON_CLICK, new EventListener() {
            public void onEvent(final Event event) throws Exception {
                final String key = "";
                Component thiscomp = event.getTarget();
                Tree tree = (Tree) thiscomp.getParent().getNextSibling();
                Collection<Treeitem> items = tree.getItems();
                if (items != null) {
                    for (Treeitem item : items) {
                        AttrSelectTreeComp.this.filterKey(item, key);
                    }
                }
            }
        });
        
        AttrCompUtil.setCompAttr(div, AttrBaseComp.COMP_VALUE_LENGTH, attrTmpl.getValueLength());
        AttrCompUtil.setCompAttr(div, AttrBaseComp.COMP_VALUE_FROM, attrTmpl.getValueFrom());
        AttrCompUtil.setCompAttr(div, AttrBaseComp.COMP_VALUE_TO, attrTmpl.getValueTo());
        AttrCompUtil.setCompAttr(div, AttrBaseComp.COMP_VALUE_REX, attrTmpl.getValidExpr());
    }
    
    /**
     * .
     * 
     * @param item Treeitem
     * @param key String
     * @return boolean
     */
    public boolean filterKey(Treeitem item, String key) {
        if (item == null) {
            return false;
        }
        boolean bool = false;
        if (item.getTreechildren() != null && item.getTreechildren().getItemCount() > 0) {
            bool = true;
        }
        if (bool) { // 有子节点
            // 如果下级返回为,显示，返回为true
            boolean chdFlag = false;
            Collection<Treeitem> chditems = item.getTreechildren().getItems();
            for (Treeitem chditem : chditems) {
                boolean ret = filterKey(chditem, key);
                if (ret = true) {
                    chdFlag = true;
                }
            }
            if (chdFlag) {
                item.setVisible(true);
                return true;
            }
            // 如果有包含关键字,显示，返回为true
            else if ((item.getLabel() + "").toLowerCase().indexOf(key) > -1) {
                item.setVisible(true);
                return true;
            }
            // 否则不显示，返回为false
        } else {
            String lab = (item.getLabel() + "").toLowerCase();
            // 如果有包含关键字,显示，返回为true
            if (lab.indexOf(key) > -1) {
                item.setVisible(true);
                return true;
            }
            // 否则不显示，返回为,false
        }
        item.setVisible(false);
        return false;
    }
    
    /**
     * 获取树
     * .
     * 
     * @param root Component
     * @return Tree
     * @author g.huangwch
     * 2011-10-26 g.huangwch
     */
    public static Tree getTree(Component root) {
        //hbox-->label||div-->pop --> div -->attrValueTreeExt
        if (root.getParent() instanceof Popup) {
            return (Tree) ((Component) root.getFirstChild().getNextSibling());
        }
        return (Tree) ((Component) root.getFirstChild().getNextSibling().getChildren().get(2))
            .getFirstChild().getLastChild();
    }
    
    /**
     * 
     * .
     * 
     * @param tree Tree
     * @param value value
     * @param comp Component
     * @author g.huangwch
     * 2011-10-26 g.huangwch
     */
    public static void setByCodeValue(final Tree tree, final String value, final Component rootcomp) {
        if (tree == null) {
            throw new IllegalArgumentException("tree must not null!");
        }
        if (value == null) {
            return;
        }
        for (final Object object : tree.getItems()) {
            final Treeitem item = (Treeitem) object;
            final String itemValue = (String) item.getValue();
            if (itemValue != null && itemValue.equals(value)) {
                // listbox.selectItem(null);
                // item.setSelected(true);
                Textbox textbox = AttrSelectTreeComp.getTextbox(rootcomp);
                textbox.setValue(item.getLabel());
                textbox.setAttribute(AttrBaseComp.COMP_PARAM1, StrUtil.strnull(item.getValue()));
                textbox.setAttribute(AttrBaseComp.COMP_PARAM2, StrUtil.strnull(item.getLabel()));
                textbox.setTooltiptext(item.getLabel());
                // bandbox.close();
                return;
            }
        }
    }
    
    /**
     * 
     * .
     * 
     * @param tree Tree
     * @param value value
     * @author g.huangwch
     * 2011-10-26 g.huangwch
     */
    public static void selectByCodeValue(final Tree tree, final String value) {
        if (tree == null) {
            throw new IllegalArgumentException("tree must not null!");
        }
        if (value == null) {
            return;
        }
        for (final Object object : tree.getItems()) {
            final Treeitem item = (Treeitem) object;
            final String itemValue = (String) item.getValue();
            if (itemValue != null && itemValue.equals(value)) {
                item.setSelected(true);
                return;
            }
        }
    }
    
    public static Textbox getTextbox(final Component rootComp) {
        if (rootComp.getParent() instanceof Popup) {
            return (Textbox) rootComp.getParent().getParent().getFirstChild();
        }
        return (Textbox) rootCompcom.xhui.vimarket.zkplus).getNextSibling().getFirstChild();
    }
    
    /**
     * {@inheritDoc}
     * @see com.xhui.vimarket.zkplus.zul.attr.mod.AttrComp
     * #getMsgComp(org.zkoss.zk.ui.Component)
     * @author wuyx
     * 2011-7-19 wuyx
     */
    @Override
    public Component getMsgComp(Component comp) {
        return getTextbox(comp);
    }
}
